package cc.c3p0.admin.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import cc.c3p0.admin.common.annotation.SystemControllerLog;
import cc.c3p0.admin.common.constants.SystemConstants;
import cc.c3p0.admin.common.dto.Json;
import cc.c3p0.admin.mybatis.model.AdminUser;
import cc.c3p0.admin.module.user.vo.UserVO;
import cc.c3p0.admin.module.user.dto.UserQueryParameter;
import cc.c3p0.admin.module.user.service.UserServiceI;
import cc.c3p0.admin.utils.JwtHelper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

/**
 * 用户管理控制器
 * @author binchao
 * 2016年10月21日
 */
@RestController
@RequestMapping("/sys/user")
public class UserController {

	private static final Logger LOG = LoggerFactory
			.getLogger(UserController.class);
	
	@Resource
	private UserServiceI userService;

	@Value("${system.jwt.secretkey}")
	private String jwtSecretKey;

	/**
	 * 注册新用户
	 * @param userInfo
	 * @return
	 */
	@RequestMapping(value = "/register")
	@SystemControllerLog
	public Json register(
			@Valid UserVO userInfo,
			BindingResult result) {
		Json json = new Json();
		if(result.hasErrors()) {
			json.setMsg("用户注册失败：" + json.handleError(result));
			return json;
		}
		try {
			userService.saveUser(userInfo);
			json.setSuccess(true);
			json.setMsg("注册成功！");
		} catch (Exception e) {
			LOG.error("用户注册失败：", e);
			json.setMsg("新用户注册失败：" + e.getMessage());
		}
		return json;
	}
	
	/**
	 * 更新用户信息
	 * @param userVO
	 * @return
	 */
	@RequestMapping(value = "/update")
	@SystemControllerLog
	public Json updateByVO(
			@Valid UserVO userVO,
			BindingResult result) {
		Json json = new Json();
		if(result.hasErrors()) {
			json.setMsg("用户更新失败：" + json.handleError(result));
			return json;
		}
		try {
			AdminUser user = new AdminUser();
			BeanUtils.copyProperties(userVO, user, "password");
			userService.update(user);
			json.setSuccess(true);
			json.setMsg("更新成功！");
		} catch (Exception e) {
			json.setMsg("更新用户信息出错：" + e.getMessage());
		}
		return json;
	}
	
	/**
	 * 修改密码
	 * @param u
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/modifyPassword", method = RequestMethod.POST)
	@SystemControllerLog
	public Json modifyPassword(UserVO u, HttpSession session) {
		Json json = new Json();
		u.setUsername(((AdminUser)session.getAttribute("user")).getUsername());
		try {
			userService.updatePassword(u);
			json.setSuccess(true);
			json.setMsg("密码更新成功！");
		} catch (Exception e) {
			LOG.error("更改密码失败：" + e.getMessage());
			json.setMsg("密码更新失败：" + e.getMessage());
		}
		return json;
	}

	@RequestMapping("/delete")
	@SystemControllerLog
	public Json delete(@RequestParam Object id) {
		Json json = new Json("信息删除成功！");
		try {
			int i = userService.delete(id);
			if (i == 1) {
				json.setSuccess(true);
			} else {
				json.setMsg("信息删除失败，信息不存在 ！");
			}
		} catch (Exception e) {
			LOG.error("信息删除失败：" + e.getMessage(), e);
			json.setMsg("信息删除失败：" + e.getMessage());
		}
		return json;
	}

	@RequestMapping("/get")
	@SystemControllerLog
	public Json get(@RequestParam String id) {
		Json json = new Json("信息获取成功！");
		try {
			AdminUser entity = userService.select(id);
			if (null != entity) {
				json.setObj(entity);
				json.setSuccess(true);
			} else {
				json.setMsg("查不到相应信息！");
			}
		} catch (Exception e) {
			LOG.error("信息获取失败：" + e.getMessage(), e);
			json.setMsg("信息获取失败：" + e.getMessage());
		}
		return json;
	}

	@RequestMapping("/find")
	@SystemControllerLog(description = "查询")
	public Json find(UserQueryParameter param) {
		Json json = new Json();
		try {
			Page<AdminUser> list = userService.find(param);
			json.setSuccess(true);
			json.setMsg("查询成功！");
			json.setObj(new PageInfo(list));
		} catch (Exception e) {
			LOG.error("查询出错：" + e.getMessage(), e);
			json.setMsg("查询出错：" + e.getMessage());
		}
		return json;
	}

	@RequestMapping("/lockOrUnlock")
	public Json lockOrUnlock(@RequestParam String id, @RequestParam String status) {
		Json json = new Json();
		AdminUser user = new AdminUser();
		user.setId(id);
		user.setStatus(status);
		try {
			userService.update(user);
			json.setSuccess(true);
			json.setMsg("启用/禁用用户成功！");
		} catch (Exception e) {
			LOG.error("启用/禁用用户出错：" + e.getMessage());
			json.setMsg("启用/禁用用户出错：" + e.getMessage());
		}
		return json;
	}

	@RequestMapping("/info")
	public Json info(@RequestParam String token) {
		Json json = new Json("用户信息获取成功！");
		try {
			Claims claims = JwtHelper.parseJWT(token, jwtSecretKey);
			String userId = (String) claims.get(SystemConstants.CURRENT_USER_ID);
			AdminUser user = userService.select(userId);
			json.setSuccess(true);
			json.setObj(user);
		} catch (Exception e) {
			LOG.error("用户信息获取失败：{}", e.getMessage());
			json.setMsg("用户信息获取失败：" + e.getMessage());
		}
		return json;
	}

	/**
	 * 用户分组
	 * @param id
	 * @param gIds
	 * @return
	 */
	@RequestMapping("/grantGroup")
	public Json grantGroup(@RequestParam String id, @RequestParam String gIds) {
		Json json = new Json("用户分组成功！");
		try {
			userService.grantGroup(id, gIds);
			json.setSuccess(true);
		} catch (Exception e) {
			LOG.error("用户分组失败：" + e.getMessage(), e);
			json.setMsg("用户分组失败：" + e.getMessage());
		}
		return json;
	}
}
